<template>
  <div class="echarts-box" :id="id" :style="styles"></div>
</template>

<script>
import { getCookie } from '@/utils/hsj';
import * as echarts from 'echarts';
import { mapGetters } from 'vuex';
export default {
  name: 'MyEchartsComponent',
  props: {
    id: String,
    echartsOptions: Object,
    styleObj: {
      // eslint-disable-next-line vue/require-valid-default-prop
      default: () => {
        return {
          width: '200rem',
          height: '200rem'
        };
      },
      type: Object
    }
  },
  data() {
    return {
      myChart: null,
      timer: null,
      styles: null
    };
  },
  computed: {
    ...mapGetters(['component'])
  },
  watch: {
    component: {
      handler(val) {
        if (val['__options__'].id === this.id && val.echarts) {
          const { width, height } = val['__commonOptions__'];
          this.styles = {
            width: width + 'rem',
            height: height + 'rem'
          };
          this.setOptions(val['__echartsOptions__']);
          this.$nextTick(() => {
            this.resizeCharts();
          });
        }
      },
      deep: true
    }
  },
  mounted() {
    const { width, height } = this.styleObj;
    this.styles = {
      width: width + 'rem',
      height: height + 'rem'
    };
    this.$nextTick(() => {
      this.drawCharts();
    });
  },
  methods: {
    // 绘制图表
    drawCharts() {
      const LoadingTextColor = {
        normal: '#333',
        dark: '#6FBDFF'
      };
      const LoadingMaskColor = {
        normal: '#fff',
        dark: 'rgba(1,4,42,0)'
      };
      let myChart = echarts.init(document.getElementById(this.id));
      myChart.clear();
      myChart.showLoading({
        text: '正在加载...',
        effect: 'whirling',
        color: '#C23431',
        maskColor: LoadingMaskColor[getCookie('themeStyle')],
        textColor: LoadingTextColor[getCookie('themeStyle')],
        textStyle: {
          fontSize: 20,
          fontWeight: 800
        }
      });
      myChart.setOption(this.echartsOptions);
      myChart.hideLoading();
      window.addEventListener('resize', function () {
        myChart.resize();
      });
      this.myChart = myChart;
    },
    // 窗口尺寸变化执行
    resizeCharts() {
      this.myChart.resize();
    },
    // 参数变化执行
    setOptions(option) {
      this.$nextTick(() => {
        this.myChart.setOption(option, true);
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.echarts-box {
  width: 100%;
  height: 100%;
}
</style>